import { Injectable } from '@nestjs/common';
import { CreateVerifySessionDto } from './dto/create-verify-session.dto';
import { InjectRepository } from "@nestjs/typeorm";
import { User } from "../users/entities/user.entity";
import { Repository } from "typeorm";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class VerifySessionService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private configService: ConfigService,
  ) {}
  async create(createVerifySessionDto: CreateVerifySessionDto) {
    if (createVerifySessionDto.operator_token !== this.configService.get<string>('PG_AGENT_SECRET'))
      return {
        data: null,
        error: {
          code: 1034,
          message: 'operator_token 错误',
        },
      };

    if (createVerifySessionDto.secret_key !== this.configService.get<string>('PG_AGENT_KEY'))
      return {
        data: null,
        error: {
          code: 1034,
          message: 'secret_key 错误',
        },
      };

    try {
      const userBuilder = this.userRepository.createQueryBuilder();
      const userOne = await userBuilder.where("uniqueToken = :uniqueToken", {uniqueToken: createVerifySessionDto.operator_player_session}).getOne()
      if(!userOne){
        return {
          data:null,
          error:{
            code: 1034,
            message:'无此用户'
          }
        }
      }
      await userBuilder
        .update(User)
        .where('id = :id', { id: userOne.id })
        .execute();

      return {
        data: {
          player_name: userOne.username,
          nickname: userOne.realName || userOne.username,
          currency: 'CNY',
        },
        error: null,
      };
    } catch (err) {
      return {
        data: null,
        error: {
          code: 1034,
          message: 'operator_player_session 错误',
        },
      };
    }
  }
}
